package com.tt.sso.controller;

import com.tt.common.Const.TtConstans;
import com.tt.common.exception.TtException;
import com.tt.common.page.TtResult;
import com.tt.common.util.CaptchaUtils;
import com.tt.common.util.CookieUtils;
import com.tt.sso.entity.RouteVo;
import com.tt.sso.entity.User;
import com.tt.sso.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录 注册 退出 等
 * @author 青青
 */
@RequestMapping("/sso")
@RestController
public class LoginController
{
    @Autowired
    private IUserService userServiceImpl;

    /**
     * 用户登录  后期加入校验
     * @param user
     * @param response
     * @param request
     * @return
     */
    @RequestMapping(value="/user/login", method= RequestMethod.POST)
    public TtResult login(@Validated User user, HttpServletResponse response, HttpServletRequest request) throws Exception
    {
        try
        {
            if (!StringUtils.isEmpty(user.getCaptcha()))
            {
                String captcha = user.getCaptcha().toLowerCase();
                String code = request.getSession().getAttribute("code").toString().toLowerCase();
                if (!captcha.equals(code))
                {
                    throw new TtException("验证码错误");
                }
            }

            TtResult result = userServiceImpl.login(user.getUserName(), user.getPassWord());

            //登录成功后写cookie
            if (result.getCode() == TtConstans.success);
            {

                //把token写入cookie
                CookieUtils.setCookie(request, response, TtConstans.TT_TOKEN, result.getData().toString());
            }
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new TtException(e.getMessage());
        }

    }

    @RequestMapping(value = "/getCaptcha", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void getCaptcha(HttpServletRequest request,HttpServletResponse response)
    {
        // 通知浏览器不要缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "-1");
        CaptchaUtils util = CaptchaUtils.Instance();

        // 将验证码输入到session中，用来验证
        String code = util.getString();
        BufferedImage image = util.getImage();
        request.getSession().setAttribute("code", code);

        // 输出打web页面
        try
        {
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    /**
     *  获取系统内的路由
     * @throws Exception
     */
    @GetMapping("/getRoute")
    public TtResult getRoute() throws Exception
    {
        RouteVo routeVo = new RouteVo();
        routeVo.setAdmin("");
        return TtResult.ok();
    }

}
